<template>
  <a-upload
      v-model:file-list="fileList"
      name="file"
      :action="baseUrl + action + packageName"
      :headers="headers"
      :accept="accept"
      :before-upload="beforeUpload"
      @change="handleChange">
    <a-button>
      <upload-outlined></upload-outlined>
      {{text}}
    </a-button>
  </a-upload>
</template>

<script lang="ts">
import {Props} from "@/components/typing";
import {defineComponent, PropType, ref, watch} from 'vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import {baseUrl} from "@/setting";
import { getToken } from '@/utils/user-util'

interface FileItem {
  uid: string;
  name?: string;
  status?: string;
  response: Props;
  url?: string;
}

interface FileInfo {
  file: FileItem;
  fileList: FileItem[];
}

export default defineComponent({
  name: "FileUpload",
  props: {
    action: {
      type: String,
      default: () => 'files/upload'
    },
    file: {
      type: Object as PropType<FileItem>,
      default: () => {
        return {} as FileItem
      }
    },
    notShow: {
      type: Boolean,
      default: () => false
    },
    text: {
      type: String,
      default: () => '文件上传'
    },
    accept: {
      type: String,
      default: () => '.xls,.xlsx,.png,.jpg,.jpeg'
    },
    packageName: {
      type: String
    }
  },
  setup(props, {emit}) {
    const fileList = ref<FileItem[]>([]);
    const path = ref('')
    const packageName = ref('')

    const handleChange = (info: FileInfo) => {
      if (info.file.status === 'done') {
        if(info.file.response.success) {
          path.value = info.file.response.data?.path
          if(props.notShow) {
            fileList.value = []
          }
          emit('success',info.file.response)
        }
      } else if (info.file.status === 'error') {
        if(props.notShow) {
          fileList.value = []
        }
        emit('error',`${info.file.name} 文件上传失败！`)
      }
    };
    const beforeUpload = () => {
      if(props.packageName) packageName.value = `?packageName=${props.packageName}`
    }
    const download = (pathValue?: string) => {
      if(!pathValue && !path.value) return;
      pathValue = pathValue ? 'WebFile/' + pathValue : 'WebFile/' + path.value
      window.open(baseUrl + pathValue)
    }
    watch(() => props.file,() => {
      fileList.value.push(props.file)
    })

    return {
      baseUrl,
      fileList,
      headers: {
        'Access-Token': getToken(),
        authorization: 'authorization-text',
      },
      packageName,
      handleChange,
      beforeUpload,
      download
    };
  },
  components: {
    UploadOutlined
  },
  emits: ['success','error']
});
</script>
